package entity.units;

import entity.Attackable;
import entity.Entity;
import loading.ImageLoader;
import math.Vector2D;

public abstract class AirUnit extends Unit implements Attacker
{
	protected static final int ATTACKING = 3;
	
	private Vector2D path;

	private Attackable target;
	
	private double attackRadius;
	private int damage;
	private double coolDown;
	private double timeUntilCoolDown;

	public AirUnit( Vector2D pos, ImageLoader img, double timeToTrain, int totalHealth, double attackRadius, int damage, double coolDown )
	{
		super( pos, img, timeToTrain, totalHealth );
		
		target = null;
		
		this.attackRadius = attackRadius;
		this.damage = damage;
		
		this.coolDown = timeUntilCoolDown = coolDown;
	}
	
	public void update( double duration )
	{
		super.update( duration );
		
		if( getState() == MOVING )
		{
			if( getPosition().distance( path ) < 15 )
				stop();
			else
				seek( path );
			
			if( target != null && ((Entity)target).getPosition().distance( this.getPosition() ) <= attackRadius  )
			{
				setState( ATTACKING );

				this.setSpeed( 0 );
			}
			
			if( target != null &&  target.isDead() )
			{
				target = null;
				
				stop();
			}
		}
		
		if( getState() == ATTACKING )
		{
			if( ((Entity)target).getPosition().distance( this.getPosition() ) > attackRadius )
			{
				goTo( ((Entity)target).getPosition() );
			}
			else if( timeUntilCoolDown >= coolDown )
			{
				target.damage( damage );
				
				timeUntilCoolDown = 0;
			}
			
			if( target.isDead() )
			{
				target = null;
				
				stop();
			}
		}
		
		if( timeUntilCoolDown < coolDown )
			timeUntilCoolDown += duration;
	}
	
	public void goTo( Vector2D end )
	{
		path = end;
	
		setState( MOVING );
	}

	public void stop()
	{
		path = null;
		setState( STANDING );
		
		this.setSpeed( 0 );
	}

	public void attack( Attackable target )
	{
		this.target = target;
		
		goTo( ((Entity)target).getPosition() );
	}
}
